圓餅圖主要是用來表示數量的占比,可以從扇形的面積觀察數量的多寡,適合用在分類少,比例有明顯差異的資料。
下載三階段人口的資料,取 110 年台灣的人口比例。
輸入資料
指定圖大小、顏色
定義弧形的內外徑
定義圓餅圖的數值
定義弧形的文字標示
把原來的資料傳入定義的 pie()
畫圖
chart = {
  
  const container = html `<svg width="900" height="500" />`
  
  const svg = d3.select(container)
  // 圓餅圖
  svg.append('g')
      .attr('class', 'donut-container')
      .attr('transform', `translate(${ width / 2 },${ height / 2 })`) // 圓心在圖的中間
      .selectAll('path')
      .data(pieArcs) // 加入弧形路徑
      .join('path')
      .style('stroke', 'white')
      .style('stroke-width', 5) 
      .style('fill', d => color( d.data.type ))
      .attr('d', arc)
  // 圓餅圖外加上文字
  const text = svg.append('g')
                  .attr('class', 'labels-container')
                  .attr('transform', `translate(${ width / 2 },${ height / 2 })`)
                  .selectAll('text')
                  .data(pieArcs)
                  .join('text')
                  .attr('transform', d => `translate(${ labelArcs.centroid(d) })`) // centroid 取弧形中間
                  .attr('text-anchor', 'middle')
  // 設定文字樣式
  text.selectAll('tspan')
    .data( d => [ 
      d.data.type, 
      d.data.value.toFixed(2) + '%' // 取到小數點後兩位,加上 %
    ])
    .join('tspan')
    .attr('x', 0)
    .style('font-family', 'sans-serif')
    .style('font-size', 14)
    .style('font-weight', (d,i) => i ? undefined : 'bold')
    .style('fill', '#0f0211') 
    .attr('dy', (d,i) => i ? '1.2em' : 0 )
    .text(d => d)
  
  return container
}
